package com.zwl.swagger.util;

import java.lang.reflect.Field;

/**
 * @author zhangweilin
 * @date 2018/7/18 10:03
 * @description: 反向工具类
 */
public class SwaggerReflectUtil {

    public static Field getField(Object target, String fieldName) throws NoSuchFieldException {
        Class<?> c = target.getClass();
        while (Object.class != c && c != null){
            try {
                Field field = c.getDeclaredField(fieldName);
                return field;
            } catch (NoSuchFieldException | SecurityException e) {
//                e.printStackTrace();
//                log.debug(c.getName()+"中未找到属性"+fieldName+"，尝试到父类中找");
            }
            c = c.getSuperclass();
        }
        return null;
    }

    /**
     * 使用反射获取变量值
     *
     * @param target    被调用对象
     * @param fieldName 被调用对象的字段，一般是成员变量或静态变量，不可以是常量
     * @param <T>       返回类型，泛型
     * @return 值
     */
    public static <T> T getFieldValue(Object target, String fieldName) {
        T value = null;
        try {
            Field f = getField(target, fieldName);
            assert f != null;
            f.setAccessible(true);
            value = (T) f.get(target);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return value;
    }

}
